import {LoginServer} from '../server/user'
import { useState } from 'react';
import {useNavigate,useSearchParams,useLocation} from  'react-router-dom'
import { parse } from '../utils';
function Home() {
  // 获取查询参数
  const location = useLocation();
  // 把location的search转换为对象
  // var search = parse(location.search); 
  var [getSearch,setSearch] = useSearchParams();
  var redirect = getSearch.getAll("redirect")||'/admin';
  // console.log( getSearch.getAll("redirect"));
  // 定义用户，设置用户的方法
  const [user,setUser] = useState({name:"",password:""})
  // 创建导航
  const navigate = useNavigate();
  function login(){
      LoginServer(user)
      .then(res=>{
        if(res.code===200){
          sessionStorage.setItem("token",res.token);
          sessionStorage.setItem("user",JSON.stringify(res.user));
          // 如果search对象有redirect属性就用redirect，没有就用/admin          
          // var  redirect = search.redirect||"/admin";
          // 跳转到redirect对应的页面
          navigate(redirect);
        }
      })
  }

  return ( <div>
    用户名：<input value={user.name} onChange={e=>setUser({...user,name:e.target.value})}/> <br/>
    密码:<input value={user.password} onChange={e=>setUser({...user,password:e.target.value})}/><br/>
    <button onClick={login}>登录</button>
  </div> );
}

export default Home;